import {UploadOutlined} from '@ant-design/icons';
import {Button, Transfer, Tree, Input, Form, message, Select, Upload} from 'antd';
import React, {useState, useRef, useEffect, Component} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {queryList, addWarehouse, removeRule, goodsTreeList, inStock} from './service';

import Access from '@/components/Access/Access';
import {PlusOutlined} from "@ant-design/icons";
import CreateForm from "./components/CreateForm";
import styles from "@/global.less";
import "./index.css";

import defaultSetting from '@/../config/defaultSettings';
const {baseUrl} = defaultSetting;
const TableList = (props) => {
  const actionRef = useRef();
  const [deleteCheck, setDeleteCheck] = useState(false);
  const [createModalVisible, handleModalVisible] = useState(false);
  const [inModalVisible, handleInModalVisible] = useState(false);
  const [treeData, setTreeData] = useState([]);
  const [record, setRecord] = useState(null);
  const [instockLoading, setInstockLoading] = useState(false);
  const [inStockBtnLoading, setInStockBtnLoading] = useState(false);

  useEffect(() => {

  }, []);

  const [targetKeys, setTargetKeys] = useState([]);
  const onChange = (keys) => {
    setTargetKeys(keys);
  };
  const columns = [
    {
      title: '仓库',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '化肥',
          status: 'Success',
        },
        2: {
          text: '超市',
          status: 'Error',
        },
        3: {
          text: '原料',
          status: 'Processing',
        },
        4: {
          text: '其他',
          status: 'Processing',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, item) => {
        return (
          <>
            <div style={{
              display: "flex",
              overflow: "hidden"
            }}>
              <Access accessKey={"@inWarehouseStock"}>
                <Button
                  type="primary"
                  danger
                  loading={inStockBtnLoading}
                  style={{
                    marginLeft: "10px"
                  }}
                  onClick={() => {
                    setInStockBtnLoading(true);
                    setRecord(item);
                    goodsTreeList(item.id).then((res) => {
                      let {code} = res;
                      if (code === 0) {
                        setTreeData([res.data]);
                        handleInModalVisible(true);
                      } else {
                        message.info(res.message);
                      }
                      setInStockBtnLoading(false);
                    });
                  }}
                >
                  入库
                </Button>
              </Access>
              <Access accessKey={"@delWarehouse"}>
                <Button
                  type="primary"
                  danger
                  loading={deleteCheck}
                  style={{
                    marginLeft: "10px"
                  }}
                  onClick={() => {
                    removeRule(item.id).then(res => {
                      actionRef.current.reload();
                    });
                  }}
                >
                  删除
                </Button>
              </Access>

            </div>
          </>
        );
      },
    },
  ];

  const oneColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'text',
      renderFormItem: () => {
        return (
          <Select placeholder="请选择类型" allowClear>
            <Select.Option value={1} key="化肥">
              化肥
            </Select.Option>
            <Select.Option value={2} key="超市">
              超市
            </Select.Option>
            <Select.Option value={3} key="原料">
              原料
            </Select.Option>
            <Select.Option value={4} key="其他">
              其他
            </Select.Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '类型为必填项',
          },
        ],
      },
    },
  ];

  const generateTree = (treeNodes = [], checkedKeys = []) => {
    return treeNodes.map(({children, ...props}) => {
      if (props.barCode){
        props.title = props.title+"("+props.barCode+")";
      }
      return {
        ...props,
        disabled: checkedKeys.includes(props.key),
        children: children ? generateTree(children, checkedKeys) : [],
      }
    });
  };

  const TreeTransfer = ({dataSource, targetKeys, ...restProps}) => {
    const transferDataSource = [];

    function flatten(list = []) {
      list.forEach((item) => {
        if (item.children && item.children.length > 0) {
          flatten(item.children);
        } else {
          transferDataSource.push(item);
        }
      });
    }

    flatten(dataSource);
    return (
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={(data) => {
          let remake = '';
          setInstockLoading(true);
          let stocks = [], fileUrls = [];
          for (let key in data) {
            if (key === 'upload') {
              if (data[key] && data[key].length > 0) {
                data[key].forEach(fileResp => {
                  if (fileResp.response && fileResp.response.code === 0) {
                    fileUrls.push(fileResp.response.data.url);
                  }
                })
              }
            }else if(key === 'remake'){
              remake = data[key];
            } else {
              stocks.push({
                id: key,
                stock: data[key]
              })
            }
          }
          if (stocks.length === 0) {
            message.info('请选择要入库的商品!');
            setInstockLoading(false);
            return;
          }
          inStock({
            id: record.id,
            type: record.type,
            stocks,
            remake,
            fileUrls
          }).then((res) => {
            if (res && res.code === 0) {
              message.success('入库成功!');
              setTargetKeys([]);
            }
            handleInModalVisible(false);
            setInstockLoading(false);
          })
        }}
        autoComplete="off"
      >
        <Transfer
          {...restProps}
          showSearch
          filterOption={(inputValue, option) => {
            return (option.title.indexOf(inputValue) > -1 || option.barCode.indexOf(inputValue) > -1);
          }}
          targetKeys={targetKeys}
          dataSource={transferDataSource}
          className="tree-transfer"
          style={{
            height: "650px",
            overflow: "scroll"
          }}
          render={(item) => {
            return <>
              <span style={{
                display: "flex",
                alignItems: "center"
              }}>
                <div
                  className="formInput"
                  style={{
                    width: "50%"
                  }}>
                  {item.title+"("+item.barCode+")"}
                </div>
                <div>
                  <Form.Item
                    className="formInput"
                    name={item.key}
                    initialValue={item.value}
                    style={{
                      marginBottom: "0",
                      float: 'right'
                    }}
                    rules={[
                      {
                        required: true,
                        pattern: '^[-]?([1-9]+[0-9]*|[0])((.[1-9])?|(.[0-9][1-9])|(.[0-9][0-9][1-9]))?$',
                        message: '[' + item.title + ']' + '数量不能为空(支持一到三位小数)!',
                      },
                    ]}
                  >
                    <Input
                      placeholder="请输入数量"
                      onClick={(e) => {
                        e.stopPropagation();
                      }}
                      onChange={(e) => {
                        item.value = e.target.value;
                      }}
                    />
                  </Form.Item>
                </div>
              </span>
            </>;
          }}
          showSelectAll={false}
        >
          {({direction, onItemSelectAll, selectedKeys, filteredItems}) => {
            if (direction === 'left') {
              const checkedKeys = [...selectedKeys, ...targetKeys];
              const target = (filteredItems.length && filteredItems.length < 10) ? generateTree(filteredItems, targetKeys) : generateTree(dataSource, targetKeys);
              return (
                <Tree
                  blockNode
                  checkable
                  checkedKeys={checkedKeys}
                  treeData={target}
                  style={{
                    height: "550px",
                    overflow: "scroll"
                  }}
                  onCheck={(_, e) => {
                    checkedKeys.splice(0, checkedKeys.length);
                    selectedKeys.splice(0, selectedKeys.length);
                    const keys = e.checkedNodes.filter(data => !data.children || data.children.length === 0).map(data => data.key);
                    onItemSelectAll(keys, true)
                  }}
                  onSelect={(_, e) => {
                    checkedKeys.splice(0, checkedKeys.length);
                    selectedKeys.splice(0, selectedKeys.length);
                    const keys = e.selectedNodes.filter(data => !data.children || data.children.length === 0).map(data => data.key);
                    onItemSelectAll(keys, true)
                  }}
                >
                </Tree>
              );
            }
          }}
        </Transfer>
        <Form.Item
          name="upload"
          style={{
            marginTop:"20px"
          }}
          labelCol={{
            span: 0, offset: 0
          }}
          label="入库单据"
          valuePropName="fileList"
          getValueFromEvent={(e) => {
            if (Array.isArray(e)) {
              return e;
            }
            return e?.fileList;
          }}
        >
          <Upload
            name="file"
            accept="image/*,.pdf"
            action={() => {
              return `${baseUrl}common/upload`;
            }}
            listType="picture"
            data={{module: "inStockPic"}}
            headers={{token: sessionStorage.getItem('token'), type: 'ADMIN'}}
          >
            <Button icon={<UploadOutlined/>}>点击上传</Button>
          </Upload>
        </Form.Item>
        <Form.Item
          name="remake"
          style={{
            marginTop:"20px"
          }}
          labelCol={{
            span: 0, offset: 0
          }}
          label="备注"
        >
          <Input placeholder="" />
        </Form.Item>
        <Form.Item
          className="formBtn"
          style={{
            textAlign: "center",
            marginTop: "48px",
            maxWidth: "100%"
          }}>
          <Button type="primary" loading={instockLoading} htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    );
  };

  return (
    <PageContainer>
      <ProTable
        headerTitle="仓库列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1400}}
        bordered
        request={(params, sorter, filter) => queryList({...params, sorter, filter})}
        postData={(payload) => {
          return payload || [];
        }}
        toolBarRender={() => [
          <Access accessKey={"@newWarehouse"}>
            <Button
              key="newWarehouseBtn"
              type="primary"
              onClick={() => {
                handleModalVisible(true);
              }}
            >
              <PlusOutlined/> 新建仓库
            </Button>
          </Access>
          ,

        ]}
        columns={columns}
        pagination={null}
      />
      <CreateForm
        title="新增仓库"
        onCancel={() => {
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
        width={800}
        btn_view={null}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            const success = await addWarehouse(value, actionRef);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
          columns={oneColumns}
        />
      </CreateForm>
      <CreateForm
        title="入库详情"
        onCancel={() => {
          handleInModalVisible(false);
        }}
        modalVisible={inModalVisible}
        width={1200}
        btn_view={null}
        className="inStockDetails"
      >
        <TreeTransfer dataSource={treeData} targetKeys={targetKeys} onChange={onChange}/>
      </CreateForm>

    </PageContainer>
  );
};

export default TableList;
